package com.woniuxy.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.woniuxy.entity.ChooseCourse;
import com.woniuxy.entity.CoachInfo;
import com.woniuxy.entity.Course;
import com.woniuxy.entity.GymCoach;
import com.woniuxy.entity.Message;
import com.woniuxy.entity.Orders;
import com.woniuxy.entity.PageBean;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.service.CoachInfoService;
import com.woniuxy.service.CoachService;
import com.woniuxy.service.GymInfoService;
import com.woniuxy.util.CommonUtil;

/**
 * 教练controller层
 * 
 * @author lishuwei
 *
 */
@Controller
@RequestMapping("/coach")
public class CoachController {
	@Autowired
	private CoachService coachService;
	@Autowired
	private GymInfoService gymInfoService;

	// 查询附近的学生
	@RequestMapping("/nearStudent")
	public List<User> nearbyStudent() {
		User user = new User().setLatitude(22.220).setLongitude(22.220);
		return null;
	}

	// 展示学生的信息
	@RequestMapping("/getUser")
	@ResponseBody
	public ResponseEntity<User> getUserInfo(Integer id) {
		ResponseEntity<User> entity = new ResponseEntity<User>();
		try {
			User student = coachService.getUserById(id);
			entity.setCode(200);
			student.setPwd("");
			entity.setData(student);
			return entity;
		} catch (Exception e) {
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}
	
	// 展示学生的信息
	@RequestMapping("/getNowUser")
	@ResponseBody
	public ResponseEntity<User> getUserInfo() {
		ResponseEntity<User> entity = new ResponseEntity<User>();
		User user = CommonUtil.getCurrentUser();
		try {
			User nowUser = coachService.getUserById(user.getId());
			entity.setCode(200);
			nowUser.setPwd("");
			entity.setData(nowUser);
			return entity;
		} catch (Exception e) {
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}


	// 展示教练的信息（课程、流派等）
	@RequestMapping("/getCoachInfo")
	@ResponseBody
	public ResponseEntity<CoachInfo> getCoachInfo(Integer id) {
		ResponseEntity<CoachInfo> entity = new ResponseEntity<CoachInfo>();
		User user = CommonUtil.getCurrentUser();
		if (user == null || "".equals(user.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}
		try {
			if ("2".equals(user.getRole())) {
				CoachInfo coachInfo = coachService.getCoachInfoById(user.getId());
				entity.setCode(200);
				entity.setData(coachInfo);
			}else if("1".equals(user.getRole())){
				CoachInfo coachInfo = coachService.getCoachInfoById(id);
				entity.setCode(200);
				entity.setData(coachInfo);
			}else {
				entity.setCode(400);
				
			}
					
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}

	// 给学员留言
	@RequestMapping("/message")
	@ResponseBody
	public ResponseEntity<Object> addMessage(Integer id, String message) {
		ResponseEntity<Object> entity = new ResponseEntity<Object>();
		User coach = CommonUtil.getCurrentUser();
		if (coach == null || "".equals(coach.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}
		try {
			Message msg = new Message().setMessageStatus("2").setContent(message).setUserIdAccepter(id)
					.setUserIdSender(coach.getId());
			coachService.sendMessage(msg);
			entity.setCode(200);
			entity.setMsg("留言成功");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}

	// 给学员留言
	@RequestMapping("/remind")
	@ResponseBody
	public ResponseEntity<Object> addMessage(Message message) {
		ResponseEntity<Object> entity = new ResponseEntity<Object>();
		User coach = CommonUtil.getCurrentUser();
		if (coach == null || "".equals(coach.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}
		try {
			coachService.sendMessage(message);
			entity.setCode(200);
			entity.setMsg("留言成功");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}

	// 约课
	@RequestMapping("/order")
	@ResponseBody
	public ResponseEntity<Object> addOrder(Orders order) {
		ResponseEntity<Object> entity = new ResponseEntity<Object>();
		User user = CommonUtil.getCurrentUser();
		if (user == null || "".equals(user.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}
		Course course =coachService.getCourseById(order.getCourseId());
		double payable = course.getPrice() * order.getCourseHour();
		try {
			if ("2".equals(user.getRole())) {//如果用户是教练
				
				
				order.setUserIdCoach(user.getId()).setOrderStatus("1").setPayable(payable).setPayed(payable)
						.setOrderTime(CommonUtil.getCurrentTime());
				coachService.addOrder(order);
				Message message = new Message();
				message.setContent(coachService.getUserById(order.getUserIdCoach()).getNickname() + "：我向您发起了私教申请，一起来战吧！！！ 上课时间时间是："
						+ order.getCourseTime() + "； 我们的课程名称是：" + order.getStyleName() + "--" + order.getCourseName() + "；时长"
						+ order.getCourseHour() + "小时，点击接受即可享受服务！").setMessageStatus("2")
						.setUserIdAccepter(order.getUserIdStudent()).setUserIdSender(order.getUserIdCoach())
						.setOrderId(order.getId());
				System.out.println(order);
				coachService.sendOrderMessage(message);
			}else if ("1".equals(user.getRole())) {
				
				
				order.setUserIdStudent(user.getId()).setOrderStatus("6").setPayable(payable).setPayed(payable)
						.setOrderTime(CommonUtil.getCurrentTime());
				coachService.addOrder(order);
				Message message = new Message();
				message.setContent(coachService.getUserById(order.getUserIdStudent()).getNickname() + "：我向您发起了私教申请，一起来战吧！！！ 上课时间时间是："
						+ order.getCourseTime() + "； 我想上的课程名称是：" + order.getStyleName() + "--" + order.getCourseName() + "；我想上"
						+ order.getCourseHour() + "小时，有时间的话点击接受带我飞！").setMessageStatus("2")
						.setUserIdAccepter(order.getUserIdCoach()).setUserIdSender(order.getUserIdStudent())
						.setOrderId(order.getId());
				System.out.println(order);
				coachService.sendOrderMessage(message);
			}
			
			
			entity.setCode(200);
			entity.setMsg("已发送申请");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}
	
	// 约课

	@RequestMapping("/choose")
	@ResponseBody
	public ResponseEntity<Object> addGymOrder(Integer chooseId) {
		ResponseEntity<Object> entity = new ResponseEntity<Object>();
		
		User user = CommonUtil.getCurrentUser();
		if (user == null || "".equals(user.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}
		
		ChooseCourse chooseCourse =coachService.getChooseCourseById(chooseId);
		
		System.out.println(chooseCourse);
		Course course =coachService.getCourseById(chooseCourse.getCourseId());
		double payable = course.getPrice() * 2;
		Orders order=new Orders();
		order.setUserIdStudent(user.getId()).setUserIdCoach(chooseCourse.getUserIdCoach()).setUserIdGym(chooseCourse.getUserIdGym()).setChooseId(chooseId);
		order.setUserIdStudent(user.getId()).setOrderStatus("6").setPayable(payable).setPayed(payable).setCourseId((int)chooseCourse.getCourseId())
		.setStyleId((int)chooseCourse.getStyleId()).setOrderTime(CommonUtil.getCurrentTime()).setCourseHour(2);
		int startHour=6+chooseCourse.getTime()*2;
		
		order.setCourseTime(chooseCourse.getDate()+" "+startHour+":00:00");
		try {
			
				
				coachService.addOrder(order);
				Message message = new Message();
				message.setContent(coachService.getUserById(order.getUserIdStudent()).getNickname() + "：你的课被我选中了，一起来战吧！！！ 上课时间时间是："
						+ order.getCourseTime() + "； 我们的课程名称是：" +  course.getCourseName() + "；我想上"
						+ order.getCourseHour() + "小时，求带我飞！").setMessageStatus("2")
						.setUserIdAccepter(order.getUserIdCoach()).setUserIdSender(order.getUserIdStudent())
						.setOrderId(order.getId());
				System.out.println(order);
				coachService.sendOrderMessage(message);
			
			
			entity.setCode(200);
			entity.setMsg("已发送申请");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");

			return entity;
		}

	}

	//签约
	@RequestMapping("/sign")
	@ResponseBody
	public ResponseEntity<Object> sign(GymCoach gymCoach, String info) {
		ResponseEntity<Object> entity = new ResponseEntity<Object>();
		User user = CommonUtil.getCurrentUser();
		if (user == null || "".equals(user.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}

		try {
			if (coachService.getGymCoachByCIdAndGid(user.getId(), gymCoach.getUserIdGym()) != 0) {
				entity.setCode(400);
				entity.setMsg("已有申请，请及时处理或等待申请结果");
				return entity;
			}
			
			gymCoach.setSginDate(CommonUtil.getCurrentTime());
			if ("2".equals(user.getRole())) {
				gymCoach.setUserIdCoach(user.getId()).setSginStatus("1");
			}else if ("3".equals(user.getRole())){
				gymCoach.setUserIdGym(user.getId()).setSginStatus("2");
			}
		
			coachService.addSgin(gymCoach, info,user.getRole());
			entity.setCode(200);
			entity.setMsg("已发送申请");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");
			return entity;
		}

	}

//获取我的签约
	@RequestMapping("/getSigns")
	@ResponseBody
	public ResponseEntity<PageBean<GymCoach>> getSgins(int page) {
		ResponseEntity<PageBean<GymCoach>> responseEntity = new ResponseEntity<>();
		try {
			User nowUser = CommonUtil.getCurrentUser();
			PageBean<GymCoach> signs = coachService.getSginsByPage(nowUser.getId(), page);
			responseEntity.setCode(1);
			responseEntity.setData(signs);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setCode(2);
		}

		return responseEntity;
	}

//获取我的学员
	@RequestMapping("/getStudents")
	@ResponseBody
	public ResponseEntity<PageBean<User>> getStudents(Integer page) {
		ResponseEntity<PageBean<User>> responseEntity = new ResponseEntity<PageBean<User>>();
		User coach = CommonUtil.getCurrentUser();
		if (coach == null || "".equals(coach.getAccount())) {
			responseEntity.setCode(2);
			responseEntity.setMsg("尚未登录，请前往登录");
			return responseEntity;
		}

		try {
			PageBean<User> pageBean = coachService.getFriendsByPage(coach.getId(), page);
			responseEntity.setData(pageBean);
			responseEntity.setCode(1);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setCode(2);
		}
		return responseEntity;
	}

	// 接受招聘
	@RequestMapping("/acceptSign")
	@ResponseBody
	public ResponseEntity<Void> acceptSign(GymCoach gymCoach) {
		ResponseEntity<Void> entity = new ResponseEntity<Void>();
		User nowUser = CommonUtil.getCurrentUser();
		if (nowUser == null || "".equals(nowUser.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}

		try {
			coachService.updateSignStatus(gymCoach, "3",nowUser.getRole());
			entity.setCode(200);
			entity.setMsg("已发送申请");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");
			return entity;
		}

	}

	// 拒绝招聘
	// 接受招聘
	@RequestMapping("/refuseSign")
	@ResponseBody
	public ResponseEntity<Void> refuseSign(GymCoach gymCoach) {
		ResponseEntity<Void> entity = new ResponseEntity<Void>();
		User nowUser = CommonUtil.getCurrentUser();
		if (nowUser == null || "".equals(nowUser.getAccount())) {
			entity.setCode(400);
			entity.setMsg("尚未登录，请前往登录");
			return entity;
		}

		try {

			coachService.updateSignStatus(gymCoach, "4",nowUser.getRole());
			entity.setCode(200);
			entity.setMsg("已发送申请");
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			entity.setCode(400);
			entity.setMsg("系统维护中");
			return entity;
		}

	}
	// 得到除去密码的其他信息
		@RequestMapping("/getUserNoPwd")
		@ResponseBody
		public ResponseEntity<Map<String, Object>> getUserNoPwd() {
			ResponseEntity<Map<String, Object>> entity = new ResponseEntity<Map<String, Object>>();
			Map<String, Object> map =new HashMap<>();
			try {
				User currentUser = CommonUtil.getCurrentUser();
				User user = coachService.getUserById(currentUser.getId());
				if ("2".equals(user.getRole())) {
					CoachInfo coachInfo = coachService.getCoachInfoById(user.getId());
					map.put("coachInfo", coachInfo);
				}
				map.put("user", user);
				entity.setCode(200);
				user.setPwd("");
				entity.setData(map);
				return entity;
			} catch (Exception e) {
				entity.setCode(400);
				entity.setMsg("系统维护中");

				return entity;
			}
}



	// 头像上传
	@RequestMapping("/updateAvatar")
	@ResponseBody
	public ResponseEntity<String> updateAvatar(HttpServletRequest request) {
		ResponseEntity<String> entity = new ResponseEntity<String>();
		String path = request.getServletContext().getRealPath("/avatar");

		// 产生一个唯一的文件名	
		String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		try {
			Part part = request.getPart("file");
//			part.getSubmittedFileName();
			// 得到Tomcat的绝对路径
			part.write(path + "/" + fileName);
			String image = "/avatar/" + fileName;
			entity.setCode(200);
			entity.setData(image);
			return entity;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			entity.setCode(400);			
			return entity;
		} // 将文件存储到指定的位置
	}

	//更新用户信息
	@RequestMapping("/updateUser")	
	@ResponseBody	
	public ResponseEntity<Void> updateUser(@RequestBody User user){
		ResponseEntity<Void> entity = new ResponseEntity<Void>();
		
		try {
			if (user.getCoachInfo() == null) {
				coachService.updateUser(user);
			} else {
				coachService.updateCoach(user);
			}
			CommonUtil.updateCurrentUser(user);
			entity.setCode(200);
			return entity;
		} catch (Exception e) {
			entity.setCode(400);		
			e.printStackTrace();
			return entity;
		}
	
	}
	

	// 展示所有场馆签约教练
	@RequestMapping("/mySginCoaches")
	@ResponseBody
	public  ResponseEntity<PageBean<User>> SginCoaches(Integer id,Integer page) {
		ResponseEntity<PageBean<User>> responseEntity = new ResponseEntity<>();
		try {
			PageBean<User> coaches = coachService.getSginCoachesByPage(id, page);
			System.out.println(coaches);
			responseEntity.setCode(1);
			responseEntity.setData(coaches);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setCode(2);
		}

		return responseEntity;
		
			
	}
}
